python


Strings are one of the most commonly used data types in Python. Whether you’re displaying messages, working with user input, or handling text data, you’ll use strings everywhere.

 
What is a String in Python?

A string is a sequence of characters enclosed in single quotes (`'`), double quotes (`"`), or triple quotes (`'''` or `"""`).

Examples:


str1 = 'Hello'
str2 = "Python"
str3 = '''This is a multi-line string'''




Creating Strings


name = "Alice"
greeting = 'Welcome to Python!'


Multi-line String:


text = """This is
a multi-line
string in Python."""




Basic String Operations

 1. Concatenation

Combine two strings using `+`:


first = "Hello"
second = "World"
print(first + " " + second)  # Output: Hello World


 2. Repetition

Repeat a string using `*`:


word = "Hi! "
print(word * 3)  # Output: Hi! Hi! Hi!


 3. Indexing

Access characters using index (starting from 0):


text = "Python"
print(text[0])  # Output: P
print(text[-1]) # Output: n (last character)


 4. Slicing

Extract part of a string:


text = "Python"
print(text[0:4])  # Output: Pyth
print(text[:3])   # Output: Pyt
print(text[2:])   # Output: thon




String Methods in Python

Python provides many built-in string methods:

 Changing Case


message = "hello world"
print(message.upper())   # HELLO WORLD
print(message.lower())   # hello world
print(message.title())   # Hello World


 Trimming Spaces


data = "   Python   "
print(data.strip())  # Removes spaces from both ends


 Finding and Replacing


text = "I love Java"
print(text.replace("Java", "Python"))  # I love Python


 Split and Join


sentence = "apple,banana,cherry"
print(sentence.split(","))  # ['apple', 'banana', 'cherry']

words = ['Hello', 'Python']
print(" ".join(words))  # Hello Python


 Check Substring


text = "Learning Python"
print("Python" in text)      # True
print("Java" not in text)    # True




String Formatting

Python offers multiple ways to format strings:

f-strings (Python 3.6+)


name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")


format() method


print("My name is {} and I am {} years old.".format("Alice", 25))




Escape Characters

Use `\` for special characters:

* `\n` – New line
* `\t` – Tab
* `\'` – Single quote
* `\"` – Double quote

Example:


print("Hello\nPython")  # Line break
print("He said, \"Python is great!\"")